package com.solocredit.finance.ui.user.act

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.Typeface
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.solocredit.finance.R
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.base.adapter.MullaOnItemChildClickListener
import com.solocredit.finance.base.utils.TitleBarUtil
import com.solocredit.finance.config.MullaConfigs
import com.solocredit.finance.databinding.ActMullaUserCheckInBinding
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.http.IHttpCallback
import com.solocredit.finance.mvp.ProAct
import com.solocredit.finance.ui.user.adapter.MullaUserSignDayAdapter
import com.solocredit.finance.utils.DateUtils
import com.solocredit.finance.utils.event.MullaEventData
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.helper.MullaCustomDataHelper
import com.solocredit.finance.utils.helper.MullaUserPointsHelper
import com.solocredit.finance.utils.helper.SharedHelper
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/8/13 10:12
 * @Annotation：
 */
class MullaUserCheckInAct: ProAct() {
    lateinit var binding: ActMullaUserCheckInBinding

    private var signDayAdapter: MullaUserSignDayAdapter? = null

    override fun getMullaRootView(): View {
        binding = ActMullaUserCheckInBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initMullaView() {
        TitleBarUtil.setStatusBarLightMode(this, false)
        binding.parentLayout.setPadding(0, TitleBarUtil.getStatusBarHeight(),0,0)
        initMullaRecyclerView()

        binding.ivLanguage.visibility = View.GONE
        if (MullaConfigs.isTanz()){
            binding.ivLanguage.visibility = View.VISIBLE
        }
    }

    override fun initMullaListener() {
        binding.imgBack.setOnClickListener {
            finish()
        }
        //客服
        binding.imgKefu.setOnClickListener {
            showMullaKefuDialog("CheckIn Page")
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_CUSTOMER,"CheckIn Page")
        }

        //语言切换
        binding.ivLanguage.setOnClickListener {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_LANGUAGE,"CheckIn Page")
            showMullaLanguageDialog("CheckIn Page", onSelectCallback = {
            })
        }

        //开启、关闭签到提醒
        binding.reminderLayout.setOnClickListener {
            showMullaLoading()
            //没有 签到提醒积分领取时间  - 没有领取过积分
            if (MullaCustomDataHelper.getMullaCustomSignReminderPointsReceiveTimestamp().isEmpty()){
                //领取积分
                val useType = "openSignReminder"
                val addPoints = MullaCustomConfigsHelper.getMullaTaskPointsByTaskId(0)
                onMullaReceivePointsAction(useType,addPoints)
            } else {
                MullaCustomDataHelper.saveMullaCustomSignReminder()
            }
        }

        //签到提醒
        binding.btnReminder.setOnClickListener {
            binding.reminderLayout.callOnClick()
        }

        //连续签到15天
        binding.btnSignMonth.setOnClickListener {
            val useType = "signFifteenDaysToMonth"
            val addPoints = MullaCustomConfigsHelper.getMullaTaskPointsByTaskId(1)
            onMullaReceivePointsAction(useType,addPoints)
        }

        //还款任务
        binding.btnRepayment.setOnClickListener {
            MyApp.app.publisher.publish(MullaEventData(MullaEventData.TYPE.MULLA_SHOW_REPAY))
            finish()
        }
    }

    override fun initMullaData() {
        showMullaUserCheckInInfo()
        showMullaSignReminderViews()

        //牌照信息
        val licenseInfo = MullaCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.addView(licenseView())
            binding.licenseLayout.visibility = View.VISIBLE
        }
    }

    /**
     * 初始化签到天数列表
     */
    private fun initMullaRecyclerView() {
//        binding.recyclerView.setHasFixedSize(true)
//        binding.recyclerView.isNestedScrollingEnabled = false
//        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
//        val topDecoration = DensityUtils.dp2px(10f)
//        binding.recyclerView.addItemDecoration(LinearSpacingItemDecoration(0,0,topDecoration,0))
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        binding.recyclerView.layoutManager = layoutManager
        signDayAdapter = MullaUserSignDayAdapter(binding.recyclerView)
        binding.recyclerView.adapter = signDayAdapter
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        signDayAdapter?.setOnItemChildClickListener(MullaOnItemChildClickListener { _, childView, position ->
            val item = signDayAdapter?.getItem(position)
            when (childView.id) {
                R.id.itemLayout -> {//点击Item

                }
            }
        })
    }

    /**
     * 设置用户签到信息
     */
    @SuppressLint("SetTextI18n")
    private fun showMullaUserCheckInInfo() {
        //连续签到天数
        val conSignTime = getMullaSignDuration()
        var showSignTime = conSignTime
        if (showSignTime > 7){
            showSignTime %= 7
        }
        val signList = arrayListOf<JSONObject>()
        for (i in 1..7){
            val item = JSONObject()
            if (i <= showSignTime){
                item.put("isSign",true)
            } else {
                item.put("isSign",false)
            }
            signList.add(item)
        }
        signDayAdapter?.data = signList

        //连续签到天数
        val showTipsText = String.format(getString(R.string.user_check_in_signed_days),"$conSignTime")
        val spString = SpannableString(showTipsText)
        val startIndex = showTipsText.indexOf("$conSignTime")
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFFFAC25")), startIndex, startIndex + "$conSignTime".length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spString.setSpan(StyleSpan(Typeface.BOLD), startIndex, startIndex + "$conSignTime".length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        binding.textSignConsecutive.text = spString

        binding.textTaskReminderPoints.text = "+${MullaCustomConfigsHelper.getMullaTaskPointsByTaskId(0)}"
        binding.textSignPoints.text = "+${MullaCustomConfigsHelper.getMullaTaskPointsByTaskId(1)}"
        binding.textRepaymentPoints.text = "+${MullaCustomConfigsHelper.getMullaTaskPointsByTaskId(2)}"
    }

    /**
     * 设置签到提醒信息
     */
    private fun showMullaSignReminderViews(){
        //是否开启签到提醒
        if (MullaCustomDataHelper.getMullaCustomIsSignReminder()){
            binding.imgReminder.setImageResource(R.mipmap.mulla_user_check_in_reminder_selected)
        } else {
            binding.imgReminder.setImageResource(R.mipmap.mulla_user_check_in_reminder_normal)
        }

        /* 签到提醒任务积分 */
        //是否领取过签到提醒积分
        if (MullaCustomDataHelper.getMullaCustomSignReminderPointsReceiveTimestamp().isEmpty()){
            binding.btnReminder.text = getString(R.string.btn_get)
            binding.btnReminder.setBackgroundResource(R.drawable.mulla_circle_fill_theme)
            binding.btnReminder.isEnabled = true
        } else {
            binding.btnReminder.text = getString(R.string.btn_done)
            binding.btnReminder.setBackgroundResource(R.drawable.mulla_circle_fill_ffe0dbee)
            binding.btnReminder.isEnabled = false
        }

        /* 本月连续签到15天任务积分 */
        // 没有上次领取时间  ->  未领取过积分
        if (MullaCustomDataHelper.getMullaCustomSignDurationPointsReceiveTimestamp().isEmpty()){
            //是否已完成 本月连续签到15天
            if (checkMullaSignDurationComplete()){
                binding.btnSignMonth.text = getString(R.string.btn_get)
                binding.btnSignMonth.setBackgroundResource(R.drawable.mulla_circle_fill_theme)
                binding.btnSignMonth.isEnabled = true
            } else {
                binding.btnSignMonth.text = getString(R.string.btn_go)
                binding.btnSignMonth.setBackgroundResource(R.drawable.mulla_circle_fill_ffe0dbee)
                binding.btnSignMonth.isEnabled = false
            }
        } else {
            // 有上次领取时间  ->  领取过积分
            //上次领取年月
            val lastDate = DateUtils.getFormatTime(MullaCustomDataHelper.getMullaCustomSignDurationPointsReceiveTimestamp().toLong() * 1000,"yyyy-MM")
            //当前年月
            val curtDate = DateUtils.getFormatTime(System.currentTimeMillis(),"yyyy-MM")

            // 上次领取年月 == 当前年月 -> 本月已领取
            if (lastDate == curtDate){
                binding.btnSignMonth.text = getString(R.string.btn_done)
                binding.btnSignMonth.setBackgroundResource(R.drawable.mulla_circle_fill_ffe0dbee)
                binding.btnSignMonth.isEnabled = false
            } else {
                //上次领取时间不是本月
                //是否已完成 本月连续签到15天
                if (checkMullaSignDurationComplete()){
                    binding.btnSignMonth.text = getString(R.string.btn_get)
                    binding.btnSignMonth.setBackgroundResource(R.drawable.mulla_circle_fill_theme)
                    binding.btnSignMonth.isEnabled = true
                } else {
                    binding.btnSignMonth.text = getString(R.string.btn_go)
                    binding.btnSignMonth.setBackgroundResource(R.drawable.mulla_circle_fill_ffe0dbee)
                    binding.btnSignMonth.isEnabled = false
                }
            }
        }
        hideMullaLoading()
    }

    /**
     * 领取分
     */
    private fun onMullaReceivePointsAction(useType: String,points: String){
        val useInfo = getString(R.string.points_use_info_task)
        MullaUserPointsHelper.saveMullsUserPointsAction(useType,useInfo,points,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        when(useType){
                            "openSignReminder" -> {
                                //积分领取成功 - 保存领取时间
                                MullaCustomDataHelper.saveMullaCustomSignReminderPointsTimestamp()
                            }
                            "signFifteenDaysToMonth" -> {
                                //积分领取成功 - 保存领取时间
                                MullaCustomDataHelper.saveMullaCustomSignDurationPointsReceiveTimestamp()
                            }
                        }
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    override fun onMullaEvent(event: MullaEventData) {
        super.onMullaEvent(event)
        if (event.eventType == MullaEventData.TYPE.MULLA_CUSTOM_DATA_REFRESHED){
            showMullaSignReminderViews()
        }
    }

    /**
     * 检查本月是否已经连续签到15天
     */
    private fun checkMullaSignDurationComplete(): Boolean{
        //连续签到天数
        val signLength = getMullaSignDuration()
        //获取当前日期
        val curtDay = DateUtils.getFormatTime(System.currentTimeMillis(),"dd")
        //连续签到时长 >= 15 && 当前日期 >= 15
        if (signLength >= 15 && curtDay.toInt() >= 15){
            return true
        }
        return false
    }

    /**
     * 获取连续签到天数
     */
    private fun getMullaSignDuration(): Int{
        val dataString = SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_SIGN_INFO)
        if (dataString.isEmpty()){
            return 1
        }
        val signInfo = JSONObject(dataString)
        return signInfo.optInt("conSignTime",1)
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_CHECK_IN_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_CHECK_IN_END)
    }

}